package cn.sc.summer.rabbitmq.util;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.sc.summer.constant.rabbit.RabbitConstant;
import cn.sc.summer.constant.util.ConvertUtil;
import cn.sc.summer.rabbitmq.po.RabbitMessage;
import cn.sc.summer.redis.util.RedisHelper;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 类名：rabbit队列工具类
 *
 * @author a-xin
 * @date 2024/3/27 16:36
 */
public class RabbitUtil {

    /**
     * 校验rabbit消息是否可靠
     *
     * @param jsonStr  消息数据
     * @param dataType 消息转换类型
     * @param <T>      消息转换泛型
     * @return 消息内容
     */
    public static <T> RabbitMessage<T> checkMessage(String jsonStr, TypeReference<T> dataType) {
        RabbitMessage<T> rabbitMessage = new RabbitMessage<>();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String randomKey = jsonObject.getString(RabbitConstant.CHECK_KEY);
        if (StrUtil.isNotBlank(randomKey) && ObjectUtil.isNotNull(RedisHelper.zGetScore(RabbitConstant.CONSUMER_KEY, randomKey))) {
            rabbitMessage.setFlag(Boolean.TRUE);
            String message = jsonObject.getOrDefault(RabbitConstant.MESSAGE_KEY, "").toString();
            if (CharSequenceUtil.isNotBlank(message)) {
                T data = ConvertUtil.toObject(message, dataType);
                rabbitMessage.setMessage(data);
            }
            RedisHelper.zRemoveMember(RabbitConstant.CONSUMER_KEY, randomKey);
        } else {
            rabbitMessage.setFlag(Boolean.FALSE);
        }
        return rabbitMessage;
    }

}
